package com.security.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.security.gateway.common.util.EncryptUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;

import javax.servlet.Filter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wangning
 * @create 2021-03-27 15:36
 */
@Configuration
public class AuthFilter extends ZuulFilter {
	@Override
	public String filterType() {
		return "pre";
	}

	@Override
	public int filterOrder() {
		return 0;
	}

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public Object run() throws ZuulException {
		//转发token
		//首先需要解析token
		//1.从上下文中取出用户身份对象
		RequestContext ctx = RequestContext.getCurrentContext();
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (!(authentication instanceof OAuth2Authentication)) {
			// 无token访问网关内资源的情况，目 前仅有uua服务直接暴露
			return null;
		}
		OAuth2Authentication oauth2Authentication = (OAuth2Authentication) authentication;
		Authentication userAuthentication = oauth2Authentication.getUserAuthentication();
		//取出用户身份
		String principal = userAuthentication.getName();
//		Object principal = userAuthentication.getPrincipal();

		//取出用户权限
		List<String> authorities = new ArrayList<>();
		userAuthentication.getAuthorities().stream().forEach(s -> authorities.add(((GrantedAuthority) s).getAuthority()));

		OAuth2Request oAuth2Request = oauth2Authentication.getOAuth2Request();

		Map<String, String> requestParameters = oAuth2Request.getRequestParameters();
		Map<String, Object> jsonToken = new HashMap<>(requestParameters);

		jsonToken.put("principal", principal);
		jsonToken.put("authorities", authorities);

		ctx.addZuulRequestHeader("json-token", EncryptUtil.encodeUTF8StringBase64(JSON.toJSONString(jsonToken)));

		return null;
	}
}
